import { Router, RouteRecordRaw } from 'vue-router'
import { useAuthUserStore } from '@/store/authUserStore'
import { menuRouteItems } from './menu'
import { ref } from 'vue'

// 使用 ref 定義響應式變量
const isDynamicRoutesAdded = ref(false)
const isErrorOccurred = ref(false)

// 提取添加路由的公共函數
const addRouteToParent = (
  router: Router,
  parentName: string,
  routerItem: RouteRecordRaw,
  meta?: Record<string, any>
) => {
  if (routerItem.component) {
    // 檢查 routerItem 是否包含必要的屬性
    if (!routerItem.path || !routerItem.name) {
      console.error('路由項缺少必要的屬性:', routerItem)
      return
    }
    const route: RouteRecordRaw = {
      path: routerItem.path,
      name: routerItem.name,
      component: routerItem.component,
      meta: meta,
    }
    router.addRoute(parentName, route)
  }
}

// 動態添加路由
const addDynamicRoutes = (router: Router, userRoutes: string[]) => {
  return new Promise<void>((resolve, reject) => {
    try {
      const basicRoute = router.getRoutes().find((route) => route.name === 'Basic')
      if (basicRoute) {
        // 將用戶有權限的路由展開
        menuRouteItems.forEach((item) => {
          const { children } = item
          const routes = children ? children : [item]
          routes.forEach((route) => {
            if (userRoutes.includes(route.name)) {
              // 過濾出有權限的路由
              addRouteToParent(router, 'Basic', route as RouteRecordRaw, {
                menu: {
                  openKey: item.name, // 父級菜單key，用於展開父級菜單，實現點擊子級菜單展開父級菜單的效果
                  selectedKey: route.name, // 選中的子級菜單key，用於高亮選中的子級菜單
                },
              }) // 添加路由
            }
          })
        })
      }
      console.log('Dynamic route loading completed')
      resolve()
    } catch (error) {
      console.error('動態添加路由時發生錯誤:', error)
      reject(error)
    }
  })
}

// 檢查是否需要登錄
const needLogin = (to: any, token: string) => {
  return to.path !== '/login' && !token
}

// 檢查是否需要動態添加路由
const needAddDynamicRoutes = (token: string, userMenus: string[]) => {
  return token && userMenus.length > 0 && !isDynamicRoutesAdded.value
}

export const setupRouterGuard = (router: Router) => {
  // 第一個全局前置守衛，處理動態路由添加和登錄驗證
  router.beforeEach(async (to, from, next) => {
    try {
      const authUserStore = useAuthUserStore()
      const { token, userMenus } = authUserStore
      if (needAddDynamicRoutes(token, userMenus)) {
        await addDynamicRoutes(router, userMenus)
        isDynamicRoutesAdded.value = true
        next({ path: to.fullPath, query: to.query, replace: true })
      } else if (needLogin(to, token)) {
        next('/login')
      } else {
        // console.log('當前Routes', router.getRoutes())
        next()
      }
    } catch (error) {
      console.error('路由守衛發生錯誤:', error)
      isErrorOccurred.value = true
      next('/error')
    }
  })
  // 第二個全局前置守衛，控制錯誤頁面和首頁的訪問
  router.beforeEach((to, from, next) => {
    if (to.path === '/') {
      return next({ name: 'Dashboard' })
    }
    if (to.path !== '/error') {
      isErrorOccurred.value = false
    } else {
      if (isErrorOccurred.value) {
        return next('/error')
      }
    }

    next() // 統一放在最後調用
  })

  //第三個守衛，處理菜單的選中狀態，實現點擊子級菜單展開父級菜單的效果，同時高亮選中的子級菜單
  router.afterEach((to) => {
    const authUserStore = useAuthUserStore()
    const { updateActiveMenu } = authUserStore
    const { selectedKey, openKey } = (to.meta?.menu as { selectedKey?: string; openKey?: string }) || {}
    if (selectedKey || openKey) {
      updateActiveMenu({ selectedKey, openKey })
    }
  })
}
